package it.giuseppetrisciuoglio.lyrics.parser;

import it.giuseppetrisciuoglio.lyrics.exception.LyricsNotFoundException;
import it.giuseppetrisciuoglio.lyrics.persistence.entity.ParserType;
import it.giuseppetrisciuoglio.lyrics.utils.StringUtilies;

import java.io.UnsupportedEncodingException;

import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractTestoParser {

	public abstract String getTesto(String httpResponse) throws LyricsNotFoundException, ParserException;
	public abstract String getURL(String artista, String titolo) throws IllegalArgumentException, UnsupportedEncodingException;
	protected final transient Logger log = LoggerFactory.getLogger(getClass());
	
	public static AbstractTestoParser getAbstractTestoParser(ParserType parserType){
		switch (parserType) {
		case AIRDAVE:
			return new AirDaveTestoParser(); 
		case LYRICSMANIA:
			return new LyricsManiaTestoParser();
		case SINGRING:
			return new SingringVirgilioTestoParser();
		case LYRICSKEEPER:
			return new LyricsKeeperTestoParser();
		case LYRICSMUSICA:
			return new LyricsMusicaTestoParser();
		case LYRICSTIME:
			return new LyricsTimeTestoParser();
		case TEKSTY:
			return new TekstyTestoParser();
		case WIKITESTI:
			return new WikiTestiTestoParser();
		case WIKIALYRICS:
			return new WikiaLyricsTestoParser();
		case LYRICSMODE:
			return new LyricsModeTestoParser();
		default:
			throw new IllegalArgumentException();
		}
	}
	
	protected String getTestoParse(String httpResponse, NodeFilter filter) throws ParserException, LyricsNotFoundException{
		Parser parser = new Parser(httpResponse);
		NodeList nodeList = parser.parse(filter);
		String responseTesto = nodeList.toHtml().trim();
		if (responseTesto == null || responseTesto.isEmpty()){
			log.error("getTestoParse(): artista or titolo is null, returning.");
			throw new LyricsNotFoundException();
		}
		return responseTesto.trim();
	}
	
	protected String cleanTitolo(String titolo){
		return StringUtilies.replaceSpecialCharVocals(titolo);
	}
	protected String cleanArtista(String artista){
		return StringUtilies.replaceSpecialCharVocals(artista);
	}
	
	protected void validArtistaAndTitolo(String artista, String titolo) throws IllegalArgumentException {
		log.debug("validArtistaAndTitolo(): artista={}, titolo={}", artista, titolo);
		if (artista == null || titolo == null || artista.isEmpty() || titolo.isEmpty()){
			log.error("validArtistaAndTitolo(): artista or titolo is null, returning.");
			throw new IllegalArgumentException();
		}
	}
}
